﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HJ_SQL_ToTable
{
    /// <summary>
    ///     将SQL导出成word文档中的表格
    /// </summary>
    public class SQLExportor
    {
        public static bool Export(string sqlFilePath, ref string msg)
        {
            if (string.IsNullOrEmpty(sqlFilePath)){
                msg = "参数为空";
                return false;
            }

            StringBuilder sbContent = ReadUtil.ReadContent(sqlFilePath);
            if (sbContent == null || sbContent.Length == 0){
                msg = "读取到的SQL内容为空";
                return false;
            }

            string content = sbContent.ToString();

            //应用正则，来查找所有的符合条件的CREATE TABLE();
            List<string> sqls = SQLSplitor.Split(content, "CREATE TABLE[^;]*;");
            if (sqls == null || sqls.Count == 0){
                msg = "未成功获取到符合条件的SQL子集";
                return false;
            }

            List<SQLTable> tables = SQLExtractor.Extract(sqls, ref msg);
            if (tables == null || tables.Count == 0)
            {
                msg = "未成功序列化SQL子集";
                return false;
            }

            int nStartIndex = 75;
            int nTableCount = 100;
            int nCurIndex = 0;

            List<SQLTable> tablesFormated = new List<SQLTable>();
            foreach (var table in tables)
            {
                if (table.Fields.Count > 2)
                {
                    nCurIndex++;
                    if (nCurIndex > nStartIndex)
                    {
                        if (tablesFormated.Count == nTableCount)
                            break;

                        tablesFormated.Add(table);
                    }
                    
                }
            }

            DocumentWriterFactory factory = new DocumentWriterFactory();
            IWriteDocument writer = factory.CreateWriter("Report");
            if (!writer.WriteDocument(Globals.ThisAddIn.Application.ActiveDocument, tablesFormated)){
                msg = "未能将SQL子集按着要求的格式写入到活动文档中！";
            }
            else {
                msg = "成功执行！";
            }

            return true;
        }
    }
}
